﻿using System.Diagnostics;
using DomainModel;
using MusicManagerDAO.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicManagerDAO.Implementation
{
    public class MusicDao : IMusicDao
    {

        static MusicDao()
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
				// richTextBox.AppendText("StockDao: using connction string \"{0}\"", ctx.Database.Connection.ConnectionString);
				Trace.WriteLine(String.Format("StockDao: using connction string \"{0}\"", ctx.Database.Connection.ConnectionString), "Information");
			}
		}

        public DomainModel.Music FindByUserIdAndName(DomainModel.User user, string name)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                var query = from s in ctx.Music
                            where s.UserId == user.Id && s.Name == name
                            select s;
                return query.FirstOrDefault().ToDomain();
            }
        }

        public IEnumerable<DomainModel.Music> FindAllForUser(DomainModel.User user)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                var query = (from s in ctx.Music.AsEnumerable()
                             where s.UserId == user.Id
                             select s.ToDomain());
                return query.ToList();
            }
        }

        public IEnumerable<DomainModel.Music> FindAll()
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                var query = (from s in ctx.Music.AsEnumerable()
                             select s.ToDomain());
                return query.ToList();
            }
        }

        public bool Insert(DomainModel.Music music)
        {
            if (MusicExists(music.Id))
                return false;

            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                ctx.Music.Add(music.ToEF());
                ctx.SaveChanges();
                return true;
            }
        }

        private bool MusicExists(int p)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                return ctx.Music.Where(s => s.Id == p).FirstOrDefault() != null;
            }
        }
    }
}
